<!--房东的主页-->
<template>
    <el-container class="landlord-container">
        <HeaderComponent />
        <el-main>
            <!-- 顶部header区域 -->
            <div class="page-header">
                <h2 class="header-title">发布的房源</h2>
                <el-button type="primary" @click="dialogVisible = true">
                    <el-icon>
                        <Plus />
                    </el-icon> 发布新房源
                </el-button>
            </div>

            <!-- 房源列表 -->
            <el-empty v-if="houses.length === 0" description="暂未发布任何房源" />

            <el-row v-else :gutter="20">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="house in houses" :key="house.id" class="mb-4">
                    <el-card :body-style="{ padding: '0px' }" class="house-card" shadow="hover">
                        <div class="image-container">
                            <img :src="house.images[0]" class="house-image">
                        </div>
                        <div class="house-info">
                            <h3 class="house-title">{{ house.title }}</h3>
                            <p class="house-address">
                                <el-icon>
                                    <Location />
                                </el-icon>{{ house.city }}市 {{ house.district }}区 {{ house.detailed_address }}
                            </p>
                            <div class="house-details">
                                <div class="detail-item">
                                    <el-icon>
                                        <House />
                                    </el-icon>
                                    <span>{{ house.rooms }}室{{ house.halls }}厅</span>
                                </div>
                                <div class="detail-item">
                                    <el-icon>
                                        <Expand />
                                    </el-icon>
                                    <span>{{ house.area }}㎡</span>
                                </div>
                                <div class="detail-item">
                                    <el-icon>
                                        <Money />
                                    </el-icon>
                                    <span>押金：¥{{ house.deposit }}</span>
                                </div>
                            </div>
                            <div class="house-status">
                                <div class="status-item">
                                    <el-icon>
                                        <Timer />
                                    </el-icon>
                                    <span>更新时间：{{ formatDate(house.updatedAt) }}</span>
                                </div>
                                <div class="status-item">
                                    <el-icon>
                                        <InfoFilled />
                                    </el-icon>
                                    <span>状态：</span>
                                    <el-tag :type="getStatusType(house.status)">{{ getStatusText(house.status)
                                        }}</el-tag>
                                </div>
                            </div>
                            <div class="house-price">
                                <span class="price">¥{{ house.price }}</span>/月
                            </div>
                            <div class="house-actions">
                                <el-button type="primary" size="small" @click="editHouse(house)">
                                    <el-icon>
                                        <Edit />
                                    </el-icon> 编辑
                                </el-button>
                                <el-button type="warning" size="small" @click="toggleHouseStatus(house)" v-if="house.status===2||house.status===3">
                                    <el-icon>
                                        <Tools />
                                    </el-icon> {{ house.status === 2 ? '设为维修' : '设为可租' }}
                                </el-button>
                                <el-button type="success" size="small" @click="republishHouse(house)" v-if="house.status===4||house.status===5">
                                    <el-icon>
                                        <Plus />
                                    </el-icon> 重新发布
                                </el-button>
                                <el-button type="danger" size="small" @click="deleteHouse(house.id)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon> 删除
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 发布/编辑房源对话框 -->
            <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑房源' : '发布新房源'" width="50%">
                <el-form :model="houseForm" label-width="100px">
                    <el-form-item label="房源标题">
                        <el-input v-model="houseForm.title" placeholder="请输入房源标题"></el-input>
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="20">
                            <el-form-item label="位置" class="location-form-item">
                                <div class="location-inputs">
                                    <div class="location-input-group">
                                        <el-input v-model="houseForm.city" placeholder="请输入城市名称"></el-input>
                                        <span class="location-label">市</span>
                                    </div>
                                    <div class="location-input-group">
                                        <el-input v-model="houseForm.district" placeholder="请输入区域名称"></el-input>
                                        <span class="location-label">区</span>
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="详细地址">
                        <el-input v-model="houseForm.detailed_address" placeholder="请输入详细地址"></el-input>
                    </el-form-item>
                    <el-form-item label="房源类型">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <el-input-number v-model="houseForm.rooms" :min="1" :max="10" size="default" />
                            <span>室</span>
                            <el-input-number v-model="houseForm.halls" :min="0" :max="5" size="default" />
                            <span>厅</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="月租金">
                        <el-input v-model="houseForm.price" placeholder="请输入月租金" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="房源面积">
                        <el-input v-model="houseForm.area" placeholder="请输入房源面积" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="押金">
                        <el-input v-model="houseForm.deposit" placeholder="请输入押金" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="描述词">
                        <el-input-tag v-model="houseForm.keywords" placeholder="请输入房屋描述词"
                            aria-label="Please click the Enter key after input" />
                    </el-form-item>
                    <el-form-item label="房源图片/视频" class="image-uploader-item">
                        <el-upload ref="uploadRef" class="house-image-uploader" v-model:file-list="imgFileList"
                            accept=".jpg,.jpeg,.png,.gif,.mp4,.webm,.avi,.mov" :limit="10" list-type="picture-card" :on-exceed="handleExceed"
                            :auto-upload="false" :on-change="handleFileChange" :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <el-dialog v-model="picDialogVisible" class="imgDetail">
                            <template v-if="isVideoFile">
                                <video controls autoplay loop muted style="width: 100%; max-height: 80vh;">
                                    <source :src="dialogImageUrl" :type="videoType">
                                    您的浏览器不支持视频播放
                                </video>
                            </template>
                            <img v-else w-full :src="dialogImageUrl" alt="Preview Image" />
                        </el-dialog>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitHouse">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-main>
    </el-container>
    <el-backtop :right="100" :bottom="100" />
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import HeaderComponent from "@/components/HeaderComponent.vue";
import { Plus, Location, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Timer, InfoFilled, Tools } from '@element-plus/icons-vue';
// 监听对话框显示状态的变化
import { watch } from 'vue';
// 导入数据请求
import apiClient from '@/api/api';
// 定义房源信息的接口类型
interface House {
    id: number;          // 房源ID
    title: string;       // 房源标题
    city: string;        // 城市
    district: string;    // 区域
    detailed_address: string;     // 详细地址
    price: number;       // 月租金
    area: number;        // 房源面积
    rooms: number;       // 房间数
    halls: number;       // 客厅数
    images: string[];    // 房源图片URL数组
    keywords: string[];  // 房源关键词
    deposit: number      // 押金
    createdAt: string; // 创建时间
    updatedAt: string; // 更新时间
    status: number; // 状态,0审核或1已租或2还未租或3维修中
}

// 使用ref创建响应式数据
const houses = ref<House[]>([]); // 存储所有房源列表
const dialogVisible = ref(false); // 控制发布/编辑房源对话框的显示状态
const isEditing = ref(false);    // 标记当前是否处于编辑模式
const uploadRef = ref(null);
// 房源表单数据
const houseForm = ref<House>({
    id: 0,
    title: '',
    city: '',
    district: '',
    detailed_address: '',
    price: 0,
    area: 0,
    rooms: 1,
    halls: 1,
    images: [],
    deposit: 0,
    keywords: [],
    createdAt: '',
    updatedAt: '',
    status: 0
});
// 图片上传相关的响应式数据
const imgFileList = ref<UploadUserFile[]>([]);
// 图片/视频预览相关的响应式数据
const dialogImageUrl = ref('')      // 预览图片/视频的URL
const picDialogVisible = ref(false) // 控制预览对话框的显示状态
const isVideoFile = ref(false)      // 标记当前预览的是否为视频文件
const videoType = ref('')           // 视频文件的MIME类型

// 临时存储上传的文件
const tempFiles = ref<File[]>([]);  // 存储待上传的图片文件
// 获取房源列表
const fetchHouses = async () => {
    try {
        //调用后端API获取房源列表
        await apiClient.get('/house/getHouseByLandlord')
            .then(
                res => {
                    if (res.data.code == 1) {
                        houses.value = res.data.data
                        console.log(houses.value)
                    } else {
                        houses.value = []
                    }
                }
            ).catch(error => {
                ElMessage.error('获取发布房源列表失败');
                houses.value = []
            })
    } catch (error) {
        ElMessage.error('获取发布房源列表失败');
    }
};

// 编辑房源
const editHouse = (house: House) => {
    // 进入编辑模式
    isEditing.value = true;
    // 将房源信息复制到表单中
    houseForm.value = { ...house };
    // 显示发布/编辑房源对话框
    dialogVisible.value = true;
    // 将图片URL转换为文件对象
    imgFileList.value = house.images.map((url) => ({
        url,
        name: url.split('/').pop()!,
        status: 'success',
    }));
};

// 删除房源
const deleteHouse = async (id: number) => {
    try {
        await ElMessageBox.confirm('确定要删除该房源吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(
            res => {
                if (res === 'confirm') {
                    apiClient.delete('/house/deleteHouse', {
                        params: {
                            id: id
                        }
                    }).then(
                        res => {
                            if (res.data.code == 1) {
                                ElMessage.success('删除成功');
                                fetchHouses()
                            } else {
                                ElMessage.error('删除失败');
                            }
                        }
                    ).catch(error => {
                        ElMessage.error('删除失败');
                    })
                }
            }
        )
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
        }
    }
};
// 上传图片限制
const handleExceed = () => {
    console.log(houseForm.value.images)
    ElMessage.warning('最多只能上传10张图片');
};

// 处理文件选择变化
const handleFileChange = (file: any) => {
    console.log('已选择文件:', file);
    // 将选择的文件添加到临时文件数组中
    tempFiles.value.push(file.raw);
};

// 处理图片移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    // 从tempFiles数组中移除对应的文件
    const index = tempFiles.value.findIndex(file => file.name === uploadFile.name);
    if (index !== -1) {
        tempFiles.value.splice(index, 1);
    }
    // 如果是编辑模式下
    if (isEditing.value) {
        // 从houseForm.value.images中移除对应的图片URL
        const index = houseForm.value.images.findIndex(url => url === uploadFile.url);
        if (index !== -1) {
            houseForm.value.images.splice(index, 1);
        }
    }
    console.log('已移除文件:', uploadFile.name);
};
// 图片/视频预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile:any) => {
    dialogImageUrl.value = uploadFile.url!
    isVideoFile.value = false
    // 检查文件类型是否为视频
    const fileName = uploadFile.name.toLowerCase();

    if (fileName.endsWith('.mp4') || fileName.endsWith('.webm') || fileName.endsWith('.avi') || fileName.endsWith('.mov')) {
        isVideoFile.value= true;
        // 设置视频MIME类型
        if (fileName.endsWith('.mp4')) videoType.value = 'video/mp4';
        else if (fileName.endsWith('.webm')) videoType.value = 'video/webm';
        else if (fileName.endsWith('.avi')) videoType.value = 'video/x-msvideo';
        else if (fileName.endsWith('.mov')) videoType.value = 'video/quicktime';
    }
    picDialogVisible.value = true
}
// 检查表单数据
const checkForm = () => {
    if (!houseForm.value.title) {
        ElMessage.error('请输入房源标题');
        return false;
    }
    if (!houseForm.value.city) {
        ElMessage.error('请输入城市');
        return false;

    }
    if (!houseForm.value.district) {
        ElMessage.error('请输入区域');
        return false;

    }
    if (!houseForm.value.detailed_address) {
        ElMessage.error('请输入详细地址');
        return false;

    }
    if (!houseForm.value.price) {
        ElMessage.error('请输入月租金');
        return false;
    }
    if (!houseForm.value.area) {
        ElMessage.error('请输入房源面积');
        return false;
    }
    if (!houseForm.value.rooms) {
        ElMessage.error('请输入房间数');
        return false;
    }
    if (!houseForm.value.halls) {
        ElMessage.error('请输入客厅数');
        return false;
    }
    if (!houseForm.value.deposit) {
        ElMessage.error('请输入押金');
        return false;
    }
    if (houseForm.value.keywords.length === 0) {
        ElMessage.error('请输入至少一个描述词');
        return false;
    }
    // 检查keywords是否有重复
    if (houseForm.value.keywords.length !== new Set(houseForm.value.keywords).size) {
        ElMessage.error('描述词中存在重复项');
        return false;
    }
    return true;
}
// 提交房源信息
const submitHouse = async () => {
    try {
        if (!checkForm()) {
            return
        }

        // 先上传所有图片和视频
        const uploadPromises = tempFiles.value.map(async (file) => {
            const formData = new FormData();
            formData.append('file', file);
            try {
                // 使用相同的API上传图片和视频
                const res = await apiClient.post('/house/uploadHouseImg', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    }
                });
                if (res.data.code === 1 && res.data.data && res.data.data.url) {
                    return res.data.data.url;
                } else {
                    throw new Error('上传失败');
                }
            } catch (error) {
                console.error('文件上传失败:', error);
                return null;
            }
        });

        // 等待所有图片上传完成
        const imageUrls = await Promise.all(uploadPromises);
        console.log('图片上传结果:', imageUrls);
        // 过滤掉上传失败的图片
        const validImageUrls = imageUrls.filter(url => url !== null&&url !== undefined);
        
        if (validImageUrls.length === 0&&!isEditing.value) {
            ElMessage.error('图片上传失败，请稍后重试');
            return;
        }
       
        // 处理图片URL
        if (isEditing.value) {
            // 编辑模式下，保留原有图片并添加新图片
            houseForm.value.images = [...houseForm.value.images, ...validImageUrls];
        } else {
            // 新建模式下，直接使用新上传的图片
            houseForm.value.images = validImageUrls;
        }
        console.log(houseForm.value.images)
        // 定义请求数据
        const data = {
            id: isEditing.value ? houseForm.value.id : 0,
            title: houseForm.value.title,
            city: houseForm.value.city,
            district: houseForm.value.district,
            detailed_address: houseForm.value.detailed_address,
            price: houseForm.value.price,
            area: houseForm.value.area,
            houseType: houseForm.value.rooms+'室'+houseForm.value.halls+'厅',
            images: houseForm.value.images,
            deposit: houseForm.value.deposit,
            keywords: houseForm.value.keywords,
        }

        // 调用后端api发布/编辑房源
        const apiUrl = isEditing.value ? '/house/updateHouse' : '/house/addHouse';
        const res = await apiClient[isEditing.value ? 'put' : 'post'](apiUrl, data);
        
        if (res.data.code === 1) {
            ElMessage.success(isEditing.value ? '更新成功' : '发布成功');
            dialogVisible.value = false;
            await fetchHouses();
            resetForm();
        } else {
            ElMessage.error(res.data.message || (isEditing.value ? '更新失败' : '发布失败'));
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error(isEditing.value ? '更新失败' : '发布失败');
    }
}
// 重置表单
const resetForm = () => {
    // 重置表单和临时文件数组
    tempFiles.value = [];
    // 清空上传组件的文件列表
    if (uploadRef.value) {
        (uploadRef.value as any).clearFiles();
    }
    houseForm.value = {
        id: 0,
        title: '',
        city: '',
        district: '',
        detailed_address: '',
        price: 0,
        area: 0,
        rooms: 1,
        halls: 1,
        images: [],
        deposit: 0,
        keywords: [],
        createdAt: '',
        updatedAt: '',
        status: 0
    };
    isEditing.value = false;
}
// 监听对话框显示状态的变化
watch(dialogVisible, (newVal) => {
    console.log('对话框显示状态变化:', newVal);
    if (!newVal) {
        // 当对话框关闭时，清空临时文件数组和表单
        resetForm()
    }
});

// 格式化日期
const formatDate = (dateString: string) => {
    return dateString.split(' ')[0];
};
// 获取房屋状态的类型
const getStatusType = (status: number) => {
    switch (status) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'warning';
        case 3: return 'danger';
        case 4: return 'danger';
        case 5: return 'danger';
        default: return 'info';
    }
};
// 获取房屋状态的文本
/*
    0审核中
    1已出租
    2空置
    3维修中
    4审核未通过
    5违规
 */
const getStatusText = (status: number) => {
    switch (status) {
        case 0: return '审核中';
        case 1: return '已出租';
        case 2: return '空置';
        case 3: return '维修中';
        case 4: return '审核未通过';
        case 5: return '违规';
        default: return '未知';
    }
};
// 修改房屋状态
const toggleHouseStatus = async (house: House) => {
    try {
        const newStatus = house.status === 2 ? 3 : 2;
        await apiClient.put('/house/updateStatus', { status: newStatus, id: house.id })
            .then(
                res => {
                    if (res.data.code == 1) {
                        house.status = newStatus
                        fetchHouses();
                        ElMessage.success('状态更新成功');
                    } else {
                        ElMessage.error(res.data.message || '状态更新失败');
                    }
                }
            ).catch(error => {
                ElMessage.error('状态更新失败');
            })
    } catch (error) {
        ElMessage.error('状态更新失败');
    }
};

// 重新发布房源
const republishHouse = async (house: House) => {
    try {
        // 确认是否重新发布
        await ElMessageBox.confirm('确定要重新发布该房源吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async res => {
            if (res === 'confirm') {
                // 调用API将房源状态改为审核中(0)
                await apiClient.put('/house/updateStatus', { status: 0, id: house.id })
                    .then(res => {
                        if (res.data.code == 1) {
                            house.status = 0;
                            fetchHouses();
                            ElMessage.success('房源已重新提交审核');
                        } else {
                            ElMessage.error(res.data.message || '重新发布失败');
                        }
                    })
                    .catch(error => {
                        ElMessage.error('重新发布失败');
                    });
            }
        });
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('重新发布失败');
        }
    }
};
// 组件挂载时获取房源列表
onMounted(async () => {
    document.title = '我的房源';
    await fetchHouses();
});
</script>

<style scoped>
.landlord-container {
    min-height: 95vh;
}

.el-main {
    padding: 20px;
    margin-top: 60px;
}

/* 添加弹窗样式 */
:deep(.el-dialog) {
    margin-top: 5vh !important;
    /* 将弹窗位置往上移动 */
}



.mb-4 {
    margin-bottom: 16px;
}

.house-card {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.image-container {
    height: 200px;
    overflow: hidden;
}

.house-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.house-info {
    padding: 14px;
}

.house-title {
    margin: 0 0 12px;
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    line-height: 1.4;
    transition: color 0.3s ease;
}

.house-card:hover .house-title {
    color: #409EFF;
}

.house-address {
    color: #606266;
    font-size: 14px;
    margin: 10px 0;
    display: flex;
    align-items: center;
    gap: 6px;
}

.house-details {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin: 12px 0;
    padding: 10px 0;
    border-top: 1px solid #ebeef5;
    border-bottom: 1px solid #ebeef5;
}

.detail-item {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #606266;
    font-size: 14px;
    transition: color 0.3s ease;
}

.house-card:hover .detail-item {
    color: #409EFF;
}

.detail-item .el-icon {
    font-size: 16px;
    color: inherit;
}

.house-price {
    color: #f56c6c;
    font-size: 14px;
    margin: 12px 0;
    font-weight: 500;
}

.price {
    font-size: 24px;
    font-weight: bold;
    margin-right: 4px;
}

.house-actions {
    display: flex;
    gap: 8px;
    margin-top: 12px;
}

.uploaded-image {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}

.imgDetail {
    width: auto;
    height: 50%;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 24px;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    border-bottom: 1px solid #ebeef5;
}

.header-title {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
    color: #303133;
    letter-spacing: 0.5px;
}

.image-uploader-item {
    width: 100%;
    border: none;
}

.location-form-item :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
}

.location-inputs {
    display: flex;
    gap: 20px;
    align-items: center;
}

.location-input-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.location-label {
    color: #606266;
    font-size: 14px;
}

.house-details {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin: 8px 0;
}

.detail-item {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #606266;
    font-size: 14px;
}

.detail-item .el-icon {
    font-size: 16px;
}

.house-status {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin: 12px 0;
    padding: 10px 0;
    border-top: 1px solid #ebeef5;
}

.status-item {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #606266;
    font-size: 14px;
}

.status-item .el-icon {
    font-size: 16px;
}
</style>
